'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 生存
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var async = require('async');
var modelUtil = require('../util/modelUtil');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var surviveSchema = require('../schemas/surviveSchema');
var Survive = mongoConnector().model('Survive');
var constantUtil = require('../util/constantUtil');

/**
 * 根据角色id获取掠夺数据
 */
module.exports.getByRoleId = function (role_id, cb) {
    function afterCreate(err, model) {
        cb(null, model);
    }

    function afterFindOne(err, schema) {
        if (!!err) {
            return cb(err);
        }
        if (!!schema) {
            return cb(null, schema);
        } else {
            Survive.create({
                role_id: role_id
            }, afterCreate);
        }
    }

    Survive.findOne({
        role_id: role_id
    }, afterFindOne);
};

// /**
//  * 5点刷新
//  */
// module.exports.onFiveRefresh = function (self, cb) {
//     this.is_end = 0;
//     this.current_wave = 0;
//     cb();
// };

/**
 * 获取当前玩家排名
 */
module.exports.getSurviveRankByRoleId = function (role_id, history_max_wave, callback) {
    var count;
    var other_count;
    async.series(
        [
            function (cb) {
                Survive.where('history_max_wave')
                    .gt(history_max_wave)
                    .count(
                        function (err, num) {
                            count = num;
                            cb();
                        });
            },
            function (cb) {
                Survive.where('history_max_wave')
                    .equals(history_max_wave)
                    .where('role_id')
                    .lt(role_id)
                    .count(
                        function (err, num) {
                            other_count = num + 1;
                            cb();
                        });
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return callback();
            }
            callback(null, count + other_count);
        }
    );
};

/**
 * 获取排行版
 *
 */
module.exports.getRank = function (cb) {
    Survive.find({})
        .sort('-history_max_wave')
        .sort('role_id')
        .limit(50)
        .select('role_id history_max_wave')
        .exec(cb);
};
